from time import sleep

from qturboframe.lib.report.log import logger
from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.lib.utils.check import CheckBasic
from qturboframe.lib.utils.CustomError.custom_error import CustomError
from qturboframe.public_ui.base_element import BaseElement
from qturboframe.public_ui.h_ui.tree import Tree


class SelectTree(BaseElement, CheckBasic):
    '''hui下拉树框控件操作'''

    def __init__(self, element_para, father=None, timeout=5):
        super().__init__(element_para, father, timeout)
        class_list = self._element.get_attribute('class').split(' ')
        if 'h-selectTree' not in class_list:
            self._element = self._element.find_element_by_attribute(
                'xpath', './ancestor::div[contains(@class, "h-selectTree")]', timeout=self.timeout)

    def set_value_for_single(self, value, timeout=20):
        """
        hui单选下拉树形框选择

        :Args:
         - value: 选择项的节点，例：XX1/XX2/XX3
         - timeout: 超时时间，默认是20s

        :Example:
         - 例: select_tree.set_value_for_single('根节点/子节点/叶子节点')
        """
        loading_ul_class = r'h-selectTree-loading'
        self._element.find_element_by_attribute(
            'css selector', 'div.h-selectTree-selection').secure_click()
        select_div = self._element.exist(
            'css selector', 'div.h-select-dropdown', timeout=0.1)
        if not select_div:
            # select_div = self._driver.find_element_by_attribute(
            #     'css selector', 'div.h-select-dropdown', 'style:display: block;', timeout=self.timeout)
            select_div = self._driver.find_element_by_attribute(
                'xpath', "//body/div[contains(@class,'h-select-dropdown') and not(contains(@style,'display: none'))]",
                timeout=self.timeout)
        timeout1 = 0
        while timeout1 < timeout * 10:
            loading_ul = select_div.exist('css selector', 'ul.' + loading_ul_class, timeout=self.timeout)
            if not loading_ul.is_displayed():
                break
            timeout1 += 1
            sleep(0.1)
        else:
            raise SeleniumError(CustomError.Error_EQ0301700_Select_Tree_No_Data)
        tree = Tree({'css selector': 'ul.h-tree'}, select_div, self.timeout)
        tree.set_value_for_single(value)

    def set_value_for_multiple(self, value=['all'], timeout=20):
        """
        hui的多选下拉树形框选择

        :Args:
         - value: 选择项的文本集合，例：[XX1/XX2/XX3, XX1/XX4/XX5]
         - timeout: 超时时间，默认是20s

        :Example:
         - 例: select_tree.set_value_for_multiple(['根节点1/子节点1/叶子节点1','根节点2/子节点2/叶子节点2'])
        """
        select_ul_class = r'h-selectTree-dropdown-list'
        # 先全部清空
        self.clear_for_multiple()
        # 弹出下拉框
        self._element.find_element_by_attribute(
            'css selector', 'div.h-selectTree-selection', timeout=self.timeout).secure_click()
        select_div = self._element.exist(
            'css selector', 'div.h-select-dropdown', timeout=0.1)
        if not select_div:
            select_div = self._driver.find_element_by_attribute(
                'xpath', "//body/div[contains(@class,'h-select-dropdown') and not(contains(@style,'display: none'))]",
                timeout=self.timeout)
        timeout1 = 0
        while timeout1 < timeout * 10:
            select_ul = select_div.exist('css selector', 'div.' + select_ul_class, timeout=self.timeout)
            if select_ul.is_displayed():
                break
            timeout1 += 1
            sleep(0.1)
        else:
            raise SeleniumError(CustomError.Error_EQ0301700_Select_Tree_No_Data)
        if len(value) == 1 and value[0] == 'all':
            select_lis = select_ul.find_elements_by_attribute('tag name', 'li', timeout=self.timeout)
            for li in select_lis:
                li.find_element_by_attribute('css selector:', 'span.h-checkbox',
                                             timeout=self.timeout).secure_click()
        else:
            tree = Tree({'css selector': 'ul.h-tree'}, select_div, self.timeout)
            tree.set_value_for_multiple(value)

    def is_default(self, value):
        """
        检查hui下拉树形框默认值

        :Args:
         - value: 待检查的选项值

        :Returns:
            匹配返回True，否则返回False

        :Example:
         - 例1: select_tree.is_default('节点1,节点2')
         - 例2: select_tree.is_default('节点1')
        """
        select_div = self._element.find_element_by_attribute(
            'css selector', 'div.h-selectTree-selection', timeout=self.timeout)
        title = select_div.get_attribute('title')
        if title:
            if value == title:
                return True
            else:
                logger.error('默认值不匹配！')
                return False
        span_default = select_div.exist(
            'css selector', 'span.h-selectTree-placeholder', timeout=self.timeout)
        if span_default and span_default.is_displayed():
            text = span_default.text
            if value == text:
                return True
            else:
                logger.error('默认值不匹配！')
                return False
        else:
            logger.error('没有默认值！')
            return False

    def is_nonnull(self):
        '''
        检查hui下拉树形框是否有非空属性

        :Returns:
            非空返回True，否则返回False

        :Example:
         - 例: select_tree.is_nonnull()
        '''
        self._element.focus()
        form_item = self._element.find_element_by_attribute(
            'xpath', './ancestor::div[contains(@class, "h-form-item-content")]/'
                     'parent::div[contains(@class, "h-form-item")]', timeout=self.timeout)
        item_class_list = form_item.get_attribute('class').split(' ')
        if 'h-form-item-required' in item_class_list:
            return True
        else:
            return False

    def clear_for_single(self):
        """
        hui单选树形下拉框清除选项值

        :Example:
         - 例: select_tree.clear_for_single()
        """
        self._element.move_to()
        clear_i = self._element.find_element_by_attribute(
            'css selector', 'div.h-selectTree-selection>i.h-icon-close', timeout=self.timeout)
        if clear_i.is_displayed():
            clear_i.secure_click()

    def clear_for_multiple(self):
        """
        hui多选树形下拉框清除选项值

        :Example:
         - 例: select_tree.clear_for_multiple()
        """
        self._element.move_to()
        clear_i = self._element.find_element_by_attribute(
            'css selector', 'div.h-selectTree-selection>i.h-icon-close', timeout=self.timeout)
        if clear_i.is_displayed():
            clear_i.secure_click()

    def check_default(self, value):
        """
        校验hui下拉树形框默认值

        :Args:
         - value: 待检查的选项值

        :Raises:
            匹配返回True，否则返回False

        :Example:
         - 例1: select_tree.check_default('节点1,节点2')
         - 例2: select_tree.check_default('节点1')
        """
        if not self.is_default(value):
            raise SeleniumError(CustomError.Error_EQ0301701_Select_Tree_Verify_Fail,'下拉树形框的默认值校验不通过！')

    def check_nonnull(self):
        '''
        校验hui下拉树形框是否有非空属性

        :Returns:
            非空返回True，否则返回False

        :Example:
         - 例: select_tree.check_nonnull()
        '''
        if not self.is_nonnull():
            raise SeleniumError(CustomError.Error_EQ0301701_Select_Tree_Verify_Fail,'下拉树形框的非空校验不通过！')
